<template>
  <div>
    <Head-Top></Head-Top>
    <div class="all_con">
      <h3 class="head_h3">
        编辑商品
      </h3>
      <el-form :model="editGoodsInfo.formDatas" status-icon :rules="rules1" ref="ruleForm" label-width="100px" class="demo-ruleForm"
               label-position="right">
        <div class="form_ctrl">
          <el-form-item label-width="0px">
            <el-button class="submit_btn" size="medium" type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button class="submit_btn" size="medium" type="default" @click="submitCancel()">取消</el-button>
          </el-form-item>
        </div>
        <div class="upload_con">
          <span class="upload_title">商品图片</span>
          <el-upload
            action="123"
            list-type="picture-card"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :on-error="errorUpload"
            :on-progress="onUpload"
            :http-request="myUpload"
            :file-list="editGoodsInfo.mainImgArr"
            multiple
            :limit="1"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <!--<el-dialog style="width: 50px" :visible.sync="dialogVisible">-->
          <!--<img width="100%" :src="dialogImageUrl" alt="">-->
          <!--</el-dialog>-->
        </div>
        <el-form-item label="名称" prop="productName">
          <el-col :span="10">
            <el-input placeholder="输入商品名" v-model="editGoodsInfo.formDatas.productName"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="商品描述" prop="points">
          <el-col :span="10">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入商品描述"
              v-model="editGoodsInfo.formDatas.points">
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="市场价格" prop="productPrice">
          <el-col :span="10">
            <el-input placeholder="输入价格(元)" type="number" v-model="editGoodsInfo.formDatas.productPrice"></el-input>
          </el-col>

        </el-form-item>
        <el-form-item label="所属展示模块" prop="moduleNumber">
          <el-col :span="10">
            <template>
              <el-radio v-model="editGoodsInfo.formDatas.moduleNumber" label="1">代理专区</el-radio>
              <el-radio v-model="editGoodsInfo.formDatas.moduleNumber" label="2">消费专区</el-radio>
            </template>
          </el-col>
        </el-form-item>

        <el-form-item label="成本价格" prop="primePrice">
          <el-col :span="10">
            <el-input placeholder="输入价格(元)" type="number" v-model="editGoodsInfo.formDatas.primePrice"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="商品库存" prop="stockNum">
          <el-col :span="10">
            <el-input placeholder="输入库存数(件)" type="number" v-model="editGoodsInfo.formDatas.stockNum"></el-input>
          </el-col>
        </el-form-item>
        <div class="upload_detail_con">
          <div class="detail_title_con">
            <div class="detail_label">
              详情图
            </div>
            <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
              <el-menu-item index="1"><i class="nmenu el-icon-picture-outline"></i>添加图片</el-menu-item>
              <!--<el-menu-item index="2"><i class="nmenu icon iconfont icon-shipin"></i>添加视频</el-menu-item>-->
              <!--<el-menu-item index="3"><i class="icon iconfont icon-icon-"></i>商品链接</el-menu-item>-->
            </el-menu>
          </div>
          <div style="margin-left: 100px;margin-top: 22px;">
            <div v-show="showDetail" class="upload_detail_img">
              <el-upload
                action="123"
                :on-remove="handleRemoveDetail"
                :before-remove="handleBeforeRemoveDetail"
                list-type="picture-card"
                :before-upload="beforeUploadDetail"
                :on-success="handleSuccessDetail"
                :on-error="errorUploadDetail"
                :file-list="editGoodsInfo.detailImgArr"
                :http-request="myUploadDetail"
              >
                <div style="display: flex;flex-direction: column;justify-content: center">
                  <span style="height: 30px;color: #8c939d">添加图片</span>
                  <i class="el-icon-plus"></i>
                </div>
              </el-upload>
            </div>
            <div v-show="showVideo" class="upload_video">
              <el-upload
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-remove="handleRemoveVideo"
                list-type="picture-card"
                :before-upload="beforeUploadVideo"
              >
                <div style="display: flex;flex-direction: column;justify-content: center">
                  <span style="height: 30px;color: #8c939d">添加视频</span>
                  <i class="el-icon-plus"></i>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
  import HeadTop from '../components/HeadTop'
  import {mapActions, mapState, mapMutations} from 'vuex'
  import {baseImgPath} from '../config/env'
  import {uploadFile} from "../api/upload";
  import  {getGoodsDetail,editGoods} from "../api/getData";
  export default {
    name: "EditGoods",
    components: {
      HeadTop
    },
    data() {
      let validateproductName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入商品名称'));
        } else {
          callback();
        }
      }
      let validateproductPrice = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入市场价格'));
        } else {
          callback();
        }
      }
      let validateCodePrice = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入成本价格'));
        } else {
          callback();
        }
      }
      let validatestockNum = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入商品库存'));
        } else {
          callback();
        }
      }
      let validatepoints = (rule, value, callback) => {
        callback();
      }
      let validatemoduleNumber = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择商品所属分类'));
        } else {
          callback();
        }
      }
      return {
        //
        rules1: {
          productName: [
            {validator: validateproductName, trigger: 'blur'}
          ],
          productPrice: [
            {validator: validateproductPrice, trigger: 'blur'}
          ],
          primePrice: [
            {validator: validateCodePrice, trigger: 'blur'}
          ],
          stockNum: [
            {validator: validatestockNum, trigger: 'blur'}
          ],
          points: [
            {validator: validatepoints, trigger: 'blur'}
          ],
          moduleNumber: [
            {validator: validatemoduleNumber, trigger: 'blur'}
          ],
        },
        uploadPath: `${baseImgPath}/product/upload`,
        activeIndex: '1',
        showDetail: true,
        showVideo: false,
        dynamicTags: ['标签一', '标签二', '标签三'],
        inputVisible: false,
        inputValue: '',
        file: '',

        productId:'',
        removeDeIndex:''
      }
    },
    methods: {
      handleSuccess(response) {
        this.goodImgSuccess(response)
        this.$message({
          type: 'success',
          message: '上传成功'
        })
      },
      errorUpload(err, file, fileList) {
        this.$message.error('上传失败，请重新上传!')
      },
      errorUploadDetail() {
        this.$message.error('上传失败，请重新上传!')
      },
      handleSuccessDetail(res) {
        this.goodDetailSuccess(res)
      },
      ...mapMutations(['setGoodsTabIndex','goodDetailSuccess','removeEGoodsD','removeEGoodsM','goodImgSuccess']),
      ...mapActions(['goodsList']),
      myUpload(content) {
        let fd = new FormData()
        fd.append('file', content.file)
        fd.append('type', 'goods')
        uploadFile(fd).done(res => {
          if (res.success) {
            this.handleSuccess(res)
          } else {
            this.errorUpload()
          }
        })
      },
      myUploadDetail(content) {
        let fd = new FormData()
        fd.append('type', 'goods')
        fd.append('file', content.file)
        uploadFile(fd).done(res => {
          if (res.success) {
            this.handleSuccessDetail(res)
          } else {
            this.errorUpload()
          }
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let ProductImages = this.editGoodsInfo.mainImg + this.editGoodsInfo.detailImg
            if(this.editGoodsInfo.mainImg==''){
              this.editGoodsInfo.$message.error('主图不能为空')
              return
            }
            if(this.editGoodsInfo.detailImg==''){
              this.$message.error('详情图不能为空')
              return
            }
            let {moduleNumber,productName,stockNum,primePrice,productPrice,points}=this.editGoodsInfo.formDatas
            let {productId}=this.editGoodsInfo
            let params={moduleNumber,productName,stockNum,primePrice,productPrice,ProductImages,points,productId}
            editGoods(params)
              .done(res=>{
                if(res.success){
                  this.$message({
                    type:'success',
                    message:'编辑成功'
                  })
                  this.setGoodsTabIndex('0')
                  this.goodsList({productName:''})
                  this.$router.replace({
                    path:'/goods'
                  })
                }
              })

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      submitCancel() {
        this.setGoodsTabIndex('0')
        this.$router.push({
          path: '/goods',
        })
      },
      beforeUploadVideo(file) {
        this.file = file
        const isLt100M = file.size / 1024 / 1024 < 100;
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) == -1) {
          this.$message.error('请上传正确的视频格式');
          return false;
        }
        if (!isLt100M) {
          this.$message.error('上传视频大小不能超过10MB哦!');
          return false;
        }
      },

      handleRemoveVideo() {

      },

      beforeUpload(file) {

      },
      onUpload(event, file, fileList) {
        console.log('event', event)
      },
      handleRemove() {
       this.removeEGoodsM(); //删除主图
      },
      handleBeforeRemoveDetail(file, fileList){
        let cIndex=''
        fileList.map((item,index)=>{
          if(item.uid==file.uid){
            cIndex=index
          }
        })
        this.removeDeIndex=cIndex
      },
      handleRemoveDetail(file, fileList) {  //删除详情图

        this.removeEGoodsD(this.cIndex)
      },
      beforeUploadDetail(file) {

      },
      handleSelect(key, keyPath) {
        if (key == 1) {
          this.showDetail = true
          this.showVideo = false
        }
        if (key == 2) {
          this.showDetail = false
          this.showVideo = true
        }
        if (key == 3) {
          this.showDetail = false
          this.showVideo = false
        }
      },
    },
    mounted(){

    },
    computed:{
      ...mapState(['editGoodsInfo']),
    },
  }
</script>

<style lang="less" scoped>
  @import "../style/table";

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .upload_con {
    display: flex;
    margin-bottom: 22px;
  }

  .upload_title {
    display: flex;
    font-size: 14px;
    color: #606266;
    width: 100px;
    justify-content: flex-end;
    align-items: flex-start;
    padding-right: 12px;
    box-sizing: border-box;
  }

  .form_ctrl {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .detail_title_con {
    display: flex;
    color: #606266;
    font-size: 14px;
  }

  .detail_label {
    width: 100px;
    padding-right: 12px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    box-sizing: border-box;
  }

  .tag_view {
    display: flex;
  }

  .tag_label {
    width: 100px;
    padding-right: 12px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    box-sizing: border-box;
    color: #606266;
    font-size: 14px;
  }

  i {
    margin-right: 5px;
  }
</style>
